//
//  PGPhotoManager.m
//  youqu
//
//  Created by 彭鹏 on 16/10/22.
//  Copyright © 2016年 pengpeng. All rights reserved.
//

#import "PGPhotoManager.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import <Photos/Photos.h>
@implementation PGPhotoManager

+ (PHAssetCollection *)fetchAssetCollections:(NSString *)title {
    PHFetchResult *result = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    for (PHAssetCollection *assetCollection in result) {
        if ([assetCollection.localizedTitle isEqualToString:title]) {
            return assetCollection;
        }
    }
    return nil;
}


+ (void)saveImage:(UIImage *)image title:(NSString *)title completionHandler:(CompletionHandler)completionHandler{
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        //判断相册是否存在
        PHAssetCollection *assetCollection = [PGPhotoManager fetchAssetCollections:title];
        
        PHAssetCollectionChangeRequest *assetCollectionChangeRequest = nil;
        if (assetCollection == nil) {
            //1.创建相册
            assetCollectionChangeRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title];
        }else {
            //存在相册
            assetCollectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
        }
        
        
        //2.创建图片请求
        PHAssetCreationRequest *assetCreationRequest = [PHAssetCreationRequest creationRequestForAssetFromImage:image];
        
        //3.往相册中添加图片
        [assetCollectionChangeRequest addAssets:@[assetCreationRequest.placeholderForCreatedAsset]];
        
        
    } completionHandler:completionHandler];
}



@end
